package com.loren.demo21.task;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Component
@AllArgsConstructor
public class TaskRegister implements DisposableBean {

    private final TaskScheduler taskScheduler;

    private static final Map<Runnable, TaskRegister.CustomTask> TASK_CONTAINER = new ConcurrentHashMap<>();

    public void addCronTask(Runnable task, String cronExpression) {
        this.addCronTask(new CronTask(task, cronExpression));
    }

    public void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable runnable = cronTask.getRunnable();
            if (TASK_CONTAINER.containsKey(runnable)) {
                removeCronTask(runnable);
            }
            TASK_CONTAINER.put(runnable, this.customTask(cronTask));
        }
    }

    public void removeCronTask(Runnable runnable) {
        TaskRegister.CustomTask scheduledTask = TASK_CONTAINER.remove(runnable);
        if (scheduledTask != null) {
            scheduledTask.cancel();
        }
    }

    public TaskRegister.CustomTask customTask(CronTask cronTask) {
        TaskRegister.CustomTask customTask = new TaskRegister.CustomTask();
        customTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return customTask;
    }

    @Override
    public void destroy() {
        for (TaskRegister.CustomTask customTask : TASK_CONTAINER.values()) {
            customTask.cancel();
        }
        TASK_CONTAINER.clear();
    }

    private static class CustomTask {

        volatile ScheduledFuture<?> future;

        public void cancel() {
            ScheduledFuture<?> future = this.future;
            if (future != null) {
                future.cancel(true);
            }
        }
    }
}
